<?php
require_once __DIR__ . "/Base_model.php";
require APPPATH . "/libraries/FFmpeg.php";
require APPPATH . "/libraries/PinYin.php";
require APPPATH . "/libraries/Ftp.php";


class Host_statics extends Base_model
{
    public function __construct()
    {
        parent::__construct();
        $this->table = "data_logs_2018";
        $this->table_video = "video";
        $this->table_statics = "data_logs_2018";
        $this->table_material = "user_material";
        $this->table_type = "type";
        $this->table_type_sub = "type_sub";
        $this->table_push_video = "push_video";
    }

    /**
     * 配音-PV
     * @param $where
     * @return array
     */
    public function pv_audio($where)
    {
        $this->db->select('count(*) AS count,b.video_join_sub,b.video_join_type,b.video_type,b.video_id,b.video_desc');
        $this->db->from("host_data_logs_2018 a");
        $this->db->join('host_video b', 'a.material_id = b.video_id');
        $arr['a.log_operate'] = 'pv';
        $arr['a.source'] = 'material';
        $arr['a.log_addtime >='] = $where['startDate'];
        $arr['a.log_addtime <='] = $where['endDate'];
        $this->db->where($arr);
        $this->db->group_by('video_id');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $datas = $res->result_array();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['video_join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['video_join_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }
        return $arr;
    }

    /**
     * 配音-UV
     * @return array
     */
    public function uv_audio($where)
    {
        $sql = "SELECT count(*) AS count,video_id,video_desc,video_id,video_join_sub,video_join_type,video_type FROM";
        $sql .= " (SELECT DISTINCT a.log_uid, DATE_FORMAT(a.log_addtime, '%y-%m-%d') AS date, b.video_desc,b.video_id,b.video_join_sub,b.video_join_type,b.video_type";
        $sql .= " FROM host_data_logs_2018 a JOIN host_video b ON a.material_id = b.video_id";
        $sql .= " WHERE a.log_operate = 'pv' AND a.source = 'material' AND a.log_addtime >= ? AND a.log_addtime <= ? ) a";
        $sql .= " GROUP BY video_id ORDER BY count DESC";

        $query = $this->db->query($sql,[$where['startDate'],$where['endDate']]);
        $datas = $query->result_array();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['video_join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['video_join_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }

        return $arr;
    }

    /**
     * 配音-分享数
     */
    public function share_audio($where)
    {
        $this->db->select('count(*) AS count,a.log_uid,a.log_addtime,b.video_join_sub,b.video_join_type,b.video_type,b.video_id,b.video_desc');
        $this->db->from("host_data_logs_2018 a");
        $this->db->join('host_video b', 'a.material_id = b.video_id');
        $arr['a.log_operate'] = 'share';
        $arr['a.source'] = 'material';
        $arr['a.log_addtime >='] = $where['startDate'];
        $arr['a.log_addtime <='] = $where['endDate'];
        $this->db->where($arr);
        $this->db->group_by('video_id');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $datas = $res->result_array();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['video_join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['video_join_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }
        return $arr;
    }

    /**
     * 配音-产出比
     */
    public function ratio_audio($where)
    {
        $data = null;

        // 获取总量
        $this->db->select('count(*) AS count,a.id,a.video_desc,a.type,b.video_id,b.video_uuid,b.video_desc,b.video_join_type,b.video_join_sub,b.video_type');
        $this->db->from("host_user_material a");
        $this->db->join('host_video b', 'a.video_uuid = b.video_id');
        $arr['a.type'] = 1;
        $arr['a.add_time >='] = $where['startDate'];
        $arr['a.add_time <='] = $where['endDate'];
        $this->db->where($arr);
        $this->db->group_by('a.video_uuid');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $dataAll = $res->result_array();


        // 获取成功量
        $arr['a.mix_status'] = 1;
        $this->db->select('count(*) AS count,a.id,a.video_desc,a.type,b.video_id,b.video_uuid,b.video_desc,b.video_join_type,b.video_join_sub,b.video_type');
        $this->db->from("host_user_material a");
        $this->db->join('host_video b', 'a.video_uuid = b.video_id');
        $this->db->where($arr);
        $this->db->group_by('a.video_uuid');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $dataSuccess = $res->result_array();

        $reData = [];
        foreach ($dataSuccess as $k => $v) {
            $reData[$v['video_uuid']] = $v;
        }

        // 计算比列
        foreach ($dataAll as $k => $v) {
            $dataAll[$k]['successCount'] = $reData[$v['video_uuid']]['count'];
            $dataAll[$k]['ratio'] = round($dataAll[$k]['successCount'] / $dataAll[$k]['count'] * 100, 2);
        }

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($dataAll as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['video_join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['video_join_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }

        return $arr;
    }

    /**
     * 配音-配音条数
     */
    public function use_count_audio($where)
    {
        $this->db->select('count(*) AS count,a.add_time,b.video_join_sub,b.video_join_type,b.video_type,b.video_id,b.video_desc');
        $this->db->from("host_user_material a");
        $this->db->join('host_video b', 'a.video_uuid = b.video_uuid');
        $arr['a.type'] = '1';
        $arr['a.add_time >='] = $where['startDate'];
        $arr['a.add_time <='] = $where['endDate'];
        $this->db->where($arr);
        $this->db->group_by('video_id');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $datas = $res->result_array();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['video_join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['video_join_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }
        return $arr;
    }


    /**
     * 视频-PV
     * @param $where
     * @param $type 类型 1.UGC视频 2.视频
     * @return array
     */
    public function pv_video($where, $type)
    {

        $this->db->select('count(*) AS count,b.join_type_sub,b.join_type,b.id,b.video_desc');
        $this->db->from("host_data_logs_2018 a");
        $this->db->join('host_user_material b', 'a.material_id = b.id');
        $arr['b.type'] = $type;
        $arr['a.log_operate'] = 'pv';
        $arr['a.source'] = 'ugc';
        $arr['a.log_addtime >='] = $where['startDate'];
        $arr['a.log_addtime <='] = $where['endDate'];
        $this->db->where($arr);
        $this->db->group_by('id');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $datas = $res->result_array();
        // echo $this->db->last_query();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['join_type_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }
        return $arr;
    }

    /**
     * 视频-UV
     * @param $where
     * @param $type 类型 1.UGC视频 2.视频
     * @return array
     */
    public function uv_video($where, $type)
    {

        $sql = "SELECT count(*) AS count,id,video_desc,join_type,join_type_sub FROM";
        $sql .= " (SELECT DISTINCT a.log_uid,DATE_FORMAT(a.log_addtime,'%y-%m-%d') AS date,b.video_desc,b.id,b.join_type_sub,b.join_type";
        $sql .= " FROM host_data_logs_2018 a JOIN host_user_material b ON a.material_id = b.id";
        $sql .= " WHERE b.type = ? and a.log_operate = 'pv' AND a.source = 'ugc' AND a.log_addtime >= ? AND a.log_addtime <= ? ) a";
        $sql .= " GROUP BY id ORDER BY count DESC";

        $query = $this->db->query($sql,[$type,$where['startDate'],$where['endDate']]);
        $datas = $query->result_array();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['join_type_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }
        return $arr;
    }

    /**
     * 视频-分享数
     * @param $where
     * @param $type 类型 1.UGC视频 2.视频
     * @return array
     */
    public function share_video($where, $type)
    {

        $this->db->select('count(*) AS count,a.log_uid,b.join_type_sub,b.join_type,b.id,b.video_desc');
        $this->db->from("host_data_logs_2018 a");
        $this->db->join('host_user_material b', 'a.material_id = b.id');
        $arr['a.log_operate'] = 'share';
        $arr['a.source'] = 'ugc';
        $arr['a.log_addtime >='] = $where['startDate'];
        $arr['a.log_addtime <='] = $where['endDate'];
        $arr['b.type ='] = $type;
        $this->db->where($arr);
        $this->db->group_by('id');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $datas = $res->result_array();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['join_type_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }
        return $arr;
    }

    /**
     * 视频-点赞数
     * @param $where
     * @param $type 类型 1.UGC视频 2.视频
     * @return array
     */
    public function zan_video($where, $type)
    {

        $this->db->select('count(*) AS count,a.add_time,b.join_type,b.join_type_sub,b.id,b.video_desc');
        $this->db->from("host_material_zan a");
        $this->db->join('host_user_material b', 'a.other_id = b.id');
        $arr['a.add_time >='] = $where['startDate'];
        $arr['a.add_time <='] = $where['endDate'];
        $arr['b.type'] = $type;
        $this->db->where($arr);
        $this->db->group_by('b.id');
        $this->db->order_by('count desc');
        $res = $this->db->get();
        $datas = $res->result_array();

        // 查询话题
        $this->db->select('*');
        $this->db->from('host_type_sub');
        $res = $this->db->get();
        $sub = $res->result_array();

        // 查询分类
        $this->db->select('*');
        $this->db->from('host_type');
        $res = $this->db->get();
        $type = $res->result_array();

        $arr = [];
        foreach ($datas as $k => $v) {
            foreach ($type as $kk => $vv) {
                if ($v['join_type'] == $vv['id']) {
                    $v['type_name'] = $vv['name'];
                }
            }
            foreach ($sub as $kk => $vv) {
                if ($v['join_type_sub'] == $vv['id']) {
                    $v['sub_name'] = $vv['sub_title'];
                }
            }
            $arr[] = $v;
        }
        return $arr;
    }

    // ---------------------------------------

    /**
     * 查询所有pv
     */
    public function all()
    {
        $this->db->select('log_id,log_ip');
        $this->db->from($this->table);
        $this->db->where("log_operate", "pv");
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 根据时间查询所有pv和uv
     */
    public function pv_uv($arr)
    {
        $this->db->select('log_id,log_ip,log_uid');
        $this->db->from($this->table);
        $this->db->where("log_operate", "pv");
        if (!empty($arr)) {
            $this->db->where("log_addtime>=", $arr['start']);
            $this->db->where("log_addtime<", $arr['end']);
        }
        $datas['total'] = $this->db->count_all_results("", false);
        $res = $this->db->get();
        $datas['row'] = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 根据时间查询所有pv和uv
     */
    public function pv_uvs($arr)
    {
        if (!empty($arr['start']) && !empty($arr['start'])) {
            $sql = "SELECT COUNT(*) FROM host_data_logs_2018 WHERE log_addtime >= ? AND log_addtime <= ? GROUP BY log_uid";
            $query = $this->db->query($sql, array($arr['start'], $arr['end']));
            return $query->result_array();
        } else {
            $sql = "SELECT COUNT(*) FROM host_data_logs_2018 GROUP BY log_uid";
            $query = $this->db->query($sql);
            return $query->result_array();
        }

    }

    /**
     *  根据时间查询所有分享
     */
    public function share($arr)
    {
        $this->db->select('log_id');
        $this->db->from($this->table);
        $this->db->where("log_operate", "share");
        if (!empty($arr)) {
            $this->db->where("log_addtime>=", $arr['start']);
            $this->db->where("log_addtime<", $arr['end']);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     *  查询所有分享
     */
    public function all_share()
    {
        $this->db->select('log_id');
        $this->db->from($this->table);
        $this->db->where("log_operate", "share");
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询点击排行名称
     */
    public function click_name()
    {
        //这是查询
        $this->db->select('video_desc,video_uuid');
        $this->db->from($this->table_video);
        $this->db->where("video_type !=", 2);
        $this->db->order_by("dub_num", "desc");
        $this->db->limit(30);
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询点击排行
     */
    public function click_detail($video_uuid, $arr)
    {
        $this->db->select('log_id');
        $this->db->from($this->table_statics);
        $this->db->where("log_uniqueid", $video_uuid);
        if (!empty($arr)) {
            $this->db->where("log_addtime>=", $arr['start']);
            $this->db->where("log_addtime<", $arr['end']);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询点击排行名称
     */
    public function click_names()
    {
        //这是查询
        $this->db->select('video_desc,video_uuid');
        $this->db->from($this->table_video);
        //        $this->db->order_by("dub_num","asc");
        $this->db->limit(30);
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询点击排行
     */
    public function click_details($video_uuid, $arr)
    {
        $this->db->select('log_id');
        $this->db->from($this->table_statics);
        $this->db->where("log_uniqueid", $video_uuid);
        if (!empty($arr['time'])) {
            $this->db->where("log_addtime>=", $arr['time']['start']);
            $this->db->where("log_addtime<", $arr['time']['end']);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询点击排行
     */
    public function produce($video_uuid, $arr)
    {
        $this->db->select('id');
        $this->db->from($this->table_material);
        $this->db->where("video_uuid", $video_uuid);
        if (!empty($arr['time'])) {
            $this->db->where("add_time>=", $arr['time']['start']);
            $this->db->where("add_time<", $arr['time']['end']);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 根据时间查询配音基础数据
     */
    public function dub_basics($arr)
    {
        $this->db->select('log_id,log_ip');
        $this->db->from($this->table_statics);
        $this->db->where("log_uniqueid !=", 0);
        if (!empty($arr)) {
            $this->db->where("log_addtime>=", $arr['start']);
            $this->db->where("log_addtime<", $arr['end']);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 根据时间查询所有pv和uv
     */
    public function dubs($arr)
    {
        if (!empty($arr['start']) && !empty($arr['start'])) {
            $sql = "SELECT COUNT(*) FROM host_data_logs_2018 WHERE log_addtime >= ? AND log_addtime <= ? AND log_uniqueid != ? GROUP BY log_uid";
            $query = $this->db->query($sql, array($arr['start'], $arr['end'], 0));
            return $query->result_array();
        } else {
            $sql = "SELECT COUNT(*) FROM host_data_logs_2018 WHERE log_uniqueid != ? GROUP BY log_uid";
            $query = $this->db->query($sql, array(0));
            return $query->result_array();
        }

    }

    /**
     * 查询配音基础数据
     */
    public function all_dub_basics()
    {
        $this->db->select('log_id,log_ip');
        $this->db->from($this->table_statics);
        $this->db->where("log_uniqueid !=", 0);
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 根据时间查出配音产出数据
     */
    Public function dub_produces($arr)
    {
        $this->db->select('id');
        $this->db->from($this->table_material);
        //        $this->db->where("log_uniqueid !=",0);
        if (!empty($arr['time'])) {
            $this->db->where("add_time>=", $arr['time']['start']);
            $this->db->where("add_time<", $arr['time']['end']);
        }
        if (!empty($arr['select_type'])) {
            $this->db->where("type", $arr['select_type']);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 根据时间查出配音产出数据
     */
    Public function all_dub_produces()
    {
        $this->db->select('id');
        $this->db->from($this->table_material);
        //        $this->db->where("log_uniqueid !=",0);
        $res = $this->db->get();
        $datas = $res->result_array();
        //        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 推送节目
     * @param $materialId
     * @param string $env
     * @return mixed code:-1.推送失败 1.推送成功
     */
    public function push($materialId, $env = 'test')
    {
        $result['code'] = -1;
        $result['msg'] = '';
        $result['data'] = '';

        error_reporting(E_ALL & ~E_NOTICE);
        $py = new Pinyin();

        // 查询视频
        $this->db->select('*');
        $this->db->from($this->table_material);
        $this->db->where("id", $materialId);
        $res = $this->db->get();
        $material = $res->row_array();

        // 视频基媒体信息
        $ffmpeg = new FFmpeg();
        $videoUrl = empty($material['user_video_url']) ? $material['video_url'] : $material['user_video_url'];
        $materialInfo = $ffmpeg->getDetail($videoUrl);

        // 查询话题
        $this->db->select('*');
        $this->db->from($this->table_type_sub);
        $this->db->where("id", $material['join_type_sub']);
        $res = $this->db->get();
        $topic = $res->row_array();

        // 构建视频
        $video["videoNameCodeF"] = $material['video_desc']; // 视频名称前半段
        $video["videoNameCodeB"] = ""; // 视频名称后半段
        $video["definition"] = "高清"; // 清晰度，待选项为：超清、高清、标清；默认为高清
        $video["imgPaths"] = [$material['pic']]; // 图片路径1
        $video["videoPaths"] = [$videoUrl]; // 视频路径
        // 码率
        $rate = ceil($materialInfo['bit_rate'] / 1000);
        if ($rate >= 1000) {
            $rate = round($rate / 1000, 1) . "M";
        } else {
            $rate = $rate . "K";
        }
        $video["videoDataRate"] = $rate; // 视频码率 1000以上的用M(1位小数),1000以下的用K(取整)
        $video["videoSize"] = $materialInfo['width'] . '*' . $materialInfo['height']; // 视频尺寸 宽*高
        $video["lengthUnit"] = 1; // 时长单位[0分 1秒 默认0]
        $video["videoLength"] = ceil($materialInfo['duration']); // 【必填】视频时长【秒】
        $video["headLength"] = ""; // 片头时长[单位默认分，可根据lengthUnit调整]
        $video["tailLength"] = ""; // 片尾时长[单位默认分，可根据lengthUnit调整]
        $video["videoPart"] = ""; // 视频文件所分章节数-M1保留字段
        $video["videoPartTime"] = ""; // 每个章节视频文件的时长-M1保留字段
        $video["createTime"] = $material['add_time'];

        // 构建节目
        $programs["id"] = $material['id']; // 【必填】
        $programs["name"] = mb_strlen($material['video_desc']) >= 24 ? $material['video_desc'] : mb_substr($material['video_desc'], 0, 24); // 【必填】名称
        $programs["alias"] = ""; // 其它名称
        $programs["subName"] = ""; // 副标题
        $programs["keywords"] = $topic['sub_title']; // 关键字 [如果多个以空格分隔]
        $programs["category"] = "综艺"; // 【必填】分类 [如果多个以空格分隔]
        $programs["sndCategory"] = '逗牛短视频'; // 【必填】二级分类 [如果多个以空格分隔]
        $programs["dsc"] = $material['video_desc'] . ' ' . $material['nick_name'] . '原创'; // 简介[20-80]
        $programs["createTime"] = $material['add_time']; // 创建时间
        $programs["source"] = ""; // 数据来源
        $programs["sourceMedia"] = ""; // 来源介质
        $programs["copyright"] = ""; // 版权方
        $programs["copyrightCode"] = ""; // 版权编码
        $programs["crBeginDate"] = ""; // 版权生效时间
        $programs["crEndDate"] = ""; // 版权失效时间
        $programs["area"] = "中国大陆"; // 【必填】国家地区
        $programs["nameInitials"] = $py->getpy($material['video_desc'], false); // 【必填】名称首字母
        $programs["year"] = date("Y", strtotime($material['add_time'])); // 【必填】年份-自动识别
        $programs["language"] = "普通话"; // 【必填】语言
        $programs["compere"] = ""; // 主持人
        $programs["producer"] = $material['nick_name']; // 制片人
        $programs["column"] = ""; // 栏目
        $programs["tvColumnId"] = ""; // 栏目Id
        $programs["poster"] = $material['pic']; // 海报
        $programs["contentProvider"] = ""; // 内容提供商
        $programs["premiereTime"] = $material['add_time']; // 【必填】首播时间
        $programs["premiereChannel"] = "逗牛短视频"; // 【必填】首播频道
        $programs["seriesNo"] = ""; // 集号
        $programs["planner"] = ""; // 策划人
        $programs["status"] = ""; // 节目状态
        $programs["onlineDate"] = ""; // 节目上线日期
        $programs["director"] = $material['nick_name']; // 【必填】导演
        $programs["screenWriter"] = ""; // 编剧
        $programs["starring"] = $material['nick_name']; // 【必填】主演/主角
        $programs["starringInitials"] = $py->getpy($material['nick_name'], false); // 【必填】主演/主角拼音
        $programs["isUnpack"] = "否"; // 是否拆条 [否/是 默认否]
        $programs["enName"] = ""; // 英文片名
        $programs["sepSeriesAmount"] = ""; // 分集总数
        $programs["prize"] = ""; // 奖项
        $programs["is4K"] = "否"; // 4K标识 [否/是 默认否]
        $programs["accesser"] = ""; // 受众
        $programs["match"] = ""; // 赛事
        $programs["reporter"] = ""; // 记者
        $programs["guest"] = ""; // 嘉宾
        $programs["subject"] = ""; // 科目
        $programs["classHour"] = ""; // 课时
        $programs["cataloger"] = ""; // 编目录入人
        $programs["others"] = ""; // 预留字段
        $programs["platform"] = "douniu"; // 平台 [wuxi:无锡/tencent:腾讯/goat:炫舞未来/hengxin:恒信/douniu:逗牛]
        $programs["deployDate"] = ""; // 发行时间
        $programs["score"] = ""; // 评分
        $programs["isTrailer"] = "否"; // 是否预告片 [否/是 默认否]
        $programs["isStock"] = "否"; // 是否回调 [否/是 默认否]
        $programs["outsideId"] = ""; // 外部来源ID

        // 构建节目集
        $data["id"] = $topic['id']; //【必填】节目集ID
        $data["name"] = mb_strlen($topic['sub_title']) >= 18 ? $topic['sub_title'] : mb_substr($topic['sub_title'], 0, 18); //【必填】名称
        $data['keywords'] = $topic['sub_title']; //【必填】关键字
        $data["alias"] = ""; //其它名称(别名)
        $data["labels"] = ''; //标签 [如果多个以空格分隔]
        $data["category"] = "综艺"; //【必填】分类 [如果多个以空格分隔]
        $data["sndCategory"] = '逗牛短视频'; //【必填】二级分类 [如果多个以空格分隔]
        $data["dsc"] = $topic['sub_desc']; //简介（20-80）
        $data["source"] = ""; //数据来源
        $data["copyright"] = ""; //版权方
        $data["copyrightCode"] = ""; //版权编码
        $data["crBeginDate"] = ""; //版权生效时间
        $data["crEndDate"] = ""; //版权失效时间
        $data["area"] = "中国大陆"; //【必填】国家地区
        $data["nameInitials"] = $py->getpy($topic['sub_title'], false); //【必填】名称首字母
        $data["year"] = date("Y", strtotime($topic['add_times'])); //年份（自动识别）
        $data["language"] = "普通话"; //【必填】语言
        $data["compere"] = ""; //主持人
        $data["producer"] = ""; //制片人
        $data["column"] = ""; //栏目
        $data["tvColumnId"] = ""; // 栏目Id
        $data["poster"] = $topic['sub_pic']; //【必填】【话题缩略横图】海报
        $data["definition"] = "高清"; //【必填】清晰度 [高清/标清等]
        $data["contentProvider"] = ""; //内容提供商
        $data["contentProviderCode"] = ""; //内容提供商编码
        $data["outerCode"] = ""; //外部数据标识
        $data["seriesAmount"] = 0; //【必填】节目总集数-默认0
        $data["playOrder"] = "降序"; //【必填】节目播放顺序（未来）[降序/升序 默认降序]
        $data["arrangeOrder"] = "降序"; //节目排序方式 [降序/升序]
        $data["videoLength"] = ""; //节目集时长 [单位分]
        $data["crInfoName"] = ""; //版权信息名称
        $data["trailerLength"] = ""; //试播时长 [单位分]
        $data["headLength"] = ""; //片头时长[单位默认分，可根据lengthUnit调整]
        $data["tailLength"] = ""; //片尾时长[单位默认分，可根据lengthUnit调整]
        $data["lengthUnit"] = 1; //时长单位[0:分 1:秒 默认0]
        $data["crInfoName"] = ""; //版权信息名称
        $data["status"] = ""; //节目集状态
        $data["priceLabels"] = ""; //节目价格标签
        $data["suggestedPrice"] = ""; //建议价格 [单位元]
        $data["score"] = ""; //评分
        $data["publishPlatform"] = ""; //发布平台
        $data["relationProgram"] = ""; //关联节目
        $data["relationColumn"] = ""; //关联栏目
        $data["epgGroup"] = ""; //EPG分组
        $data["createTime"] = $topic['add_times']; //创建时间
        $data["statusChangeTime"] = ""; //状态修改时间
        $data["operator"] = ""; //操作人
        $data["is3D"] = "否"; //是否3D [否/是 默认否]
        $data["isTrailer"] = "否"; //是否预告片 [否/是 默认否]
        $data["director"] = "无"; //【必填】导演
        $data["screenWriter"] = ""; //编剧
        $data["starring"] = "无"; //【必填】主演/主角
        $data["starringInitials"] = "无"; //【必填】主演/主角拼音
        $data["enName"] = ""; //英文片名
        $data["premiereChannel"] = "逗牛短视频"; //【必填】首播频道
        $data["premiereTime"] = ""; //首播时间
        $data["newestSeriesNo"] = ""; //节目最新集数
        $data["prize"] = ""; //奖项
        $data["is4K"] = "否"; //4K标识 [否/是 默认否]
        $data["deployDate"] = ""; //发行时间
        $data["accesser"] = ""; //受众
        $data["seriesPeriod"] = ""; //期数
        $data["match"] = ""; //赛事
        $data["reporter"] = ""; //记者
        $data["guest"] = ""; //嘉宾
        $data["subject"] = ""; //科目
        $data["classHour"] = ""; //课时
        $data["singer"] = ""; //歌手
        $data["cataloger"] = ""; //编目录入人
        $data["others"] = ""; //预留字段
        $data["platform"] = "douniu"; //平台 [wuxi:无锡/tencent:腾讯/goat:炫舞未来/hengxin:恒信/douniu:逗牛]
        $data["isStock"] = "否"; //是否回调 [否/是 默认否]
        $data["outsideSetId"] = ""; //外部来源ID

        // 上传视频文件到FTP - 需要处理成绝度路径
        $uploadResult = $this->uploadFileToFtp($videoUrl); // 1.成功 -1，失败
        if ($uploadResult['code'] != 1) {
            // 日志记录
            $inData['set_id'] = $data['id'];
            $inData['post_data'] = json_encode($data, JSON_UNESCAPED_UNICODE);
            $inData['add_time'] = date('Y-m-d H:i:s');
            $inData['status_push_video'] = -1;
            $inData['err_data'] = json_encode($uploadResult, JSON_UNESCAPED_UNICODE);;
            $this->db->insert($this->table_push_video, $inData);
            return $uploadResult;
        }else{
            // 构建data结构
            $video["videoPaths"] = [$uploadResult['fileFtpPath']];
            $videos[] = $video;
            $programs["videos"] = $videos;
            $data["programs"][] = $programs;
        }

        // 进行推送  {{HOST}}/service/program/{{PLATFORM}}/push
        // 现在都是测试地址
        $pushUrl = $env == 'product' ? 'https://stage-bzo.cloud.ottcn.com/piper/service/program/douniu/push' : 'https://stage-bzo.cloud.ottcn.com/piper/service/program/douniu/push';
        $data_string = json_encode($data);
        $ch = curl_init($pushUrl);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data_string)
        ));
        $curlResult = curl_exec($ch);
        if (curl_errno($ch)) {
            print curl_error($ch);
        }
        curl_close($ch);
        $curlResArr = json_decode($curlResult, true);

        // 处理推送结果
        if ($curlResArr['code'] == 1) {
            // 推送成功
            $inData['status_push_data'] = 1;
            $result['code'] = 1;
            $result['msg'] = '推送成功：'.$curlResult;
        } else {
            // 推送失败
            $inData['status_push_data'] = 0;
            $result['code'] = -1;
            $result['msg'] = '推送失败：'.$curlResult;
        }
        $result['data'] = $data;

        // 日志记录
        $inData['set_id'] = $data['id'];
        $inData['post_data'] = json_encode($data, JSON_UNESCAPED_UNICODE);
        $inData['add_time'] = date('Y-m-d H:i:s');
        $inData['status_push_video'] = 2;
        $inData['content'] = $curlResult;
        $this->db->insert($this->table_push_video, $inData);

        return $result;
    }

    /**
     * 推送视频到FTP
     * @param string $fileUrl
     * @return bool
     */
    public function uploadFileToFtp($fileUrl = '')
    {
        $result['code'] = -1;
        $result['msg'] = '';
        $result['data'] = '';

        $config['host'] = '111.32.132.218';
        $config['user'] = 'douniu';
        $config['pass'] = 'io5aep9Zi6Ah';
        $ftp = new Ftp($config);
        $conn = $ftp->connect();
        if (!$conn) {
            $result['msg'] = $ftp->get_error_msg();
        } else {
            $result['msg'] = '链接成功';
        }


        $rootPath = "/data0/dk/cdn/host";
        $host = 'https://s-js.sports.cctv.com/host';
        $localFilePath = str_replace($host, $rootPath, $fileUrl); // 源文件
        // $localFilePath = "/data0/dk/cdn/host/mv/1544884984_15439097014989.mp4";

        $path_arr = explode('/', $localFilePath); // 取目录数组
        $file_name = array_pop($path_arr); // 弹出文件名
        $remoteFile = date('Y/m/d/').$file_name; // 目标文件
        // $remoteFile = trim(str_replace($rootPath, "", $localFilePath), "/"); // 目标文件

        // 推送的目录调整为 /YYYY/MM/DD/xxxx.suffix 如 /2018/12/20/xxxx.mp4

        //上传文件
        if ($ftp->upload($localFilePath, $remoteFile)) {
            $result['code'] = 1;
            $result['msg'] = '上传FTP成功';
            $result['data'] = '';
            $result['fileFtpPath'] = '/'.$remoteFile;
        } else {
            $result['code'] = -1;
            $result['msg'] = '上传FTP失败:' . $ftp->get_error_msg();
            $result['data'] = $fileUrl;
        }

        $ftp->close();

        return $result;

    }
}